<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="客户代码" prop="customerCode">
        <el-input
          v-model="queryParams.customerCode"
          placeholder="请输入客户代码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
     
      <el-form-item>
        <el-button @click="handleQuery" type="primary">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div style="width: 100%; height: 50px; display: flex; justify-content: space-between">
      <div>
        <el-button
          type="primary"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['produce:course-blanking:export']"
        >
          数据导出
        </el-button>
      </div>
      <el-button type="primary" @click="openTableTitleSet"> 表头设置 </el-button>
    </div>
    <el-table
      ref="multipleTableRef"
      border
      :summary-method="getSummaries"
      show-summary
      row-key="id"
      :height="tableHeight"
      :tree-props="{ children: 'children' }"
      default-expand-all
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        align="center"
        :selectable="isSelected"
        :reserve-selection="true"
        type="selection"
        fixed="left"
        width="80"
      />
      <el-table-column label="序号" align="center" type="index" fixed="left" width="80"/>
      <template v-for="(item, index) in tableTitleList">
        <el-table-column
        v-if="item.isTable && item.label != '序号'"
          :key="index"
          :type="item.type"
          :min-width="item.width"
          :header-align="item.headerAlign"
          :align="item.align"
          :label="item.label"
          :prop="item.field"
        >
          <template #default="scope">
            <dict-tag v-if="item.dictType" :type="item.dictType" :value="scope.row[item.field]" />
              <span v-else>{{ scope.row[item.field] }}</span>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
  <!-- 表头设置 -->
  <TableWidthSet ref="tableTitleSet" @refresh="getList" />
</template>

<script setup lang="ts" name="salaryCostProject">
  // import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import type { CrudSchema } from '@/hooks/web/useCrudSchemas'
  import download from '@/utils/download'
  import * as salaryCostProjectApi from '@/api/payroll/costQuery/salaryCostProject'
  const total = ref(0) // 列表的总页数
  const list = ref<any[]>([]) // 列表的数据
  const tableTitleList = ref<CrudSchema[]>([]) // 表头列表
  const multipleTableRef = ref()
  const loading = ref(false) // 列表的加载中
  const isEdit = ref(false) //是否指派

  const queryParams = reactive({
    pageNo: 1,
    pageSize: 50,
    customerCode: undefined,
    productName: undefined,
  })
  const queryFormRef = ref() // 搜索的表单
  const exportLoading = ref(false) // 导出的加载中
  const getSummaries = (param) => {
    const { columns, data } = param;
      const sums:string[] = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }
        if (["blanking","machining","welding","assembly","paint","wiring","electric","machine","management","subtotal","publicShare","amount"].includes(column.property)) {
          const values = data.map((item) => Number(item[column.property]));
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return (parseFloat(prev) + parseFloat(curr)).toFixed(2);
              } else {
                return parseFloat(prev).toFixed(2);
              }
            }, 0);
          } else {
            sums[index] = "";
          }
        }
      });

      return sums;
  }
  /**数据 */
  const getList = async () => {
    loading.value = true
    try {
      const data = await salaryCostProjectApi.getSalaryCostProjectPage(queryParams)
      list.value = data.list
      tableTitleList.value = data.labels
      total.value = data.total
      loading.value = false
    } finally {
      loading.value = false
    }
  }

  // 多选是否启用
  const isSelected = (row) => {
    if (isEdit.value) {
      if (row.dictReportWay === 10) {
        return true
      } else {
        return row.parent !== undefined ? true : false
      }
    } else {
      return true
    }
  }

  /**选中 */
  const selectList = ref<any[]>([])
  const handleSelectionChange = (data) => {
    selectList.value = data
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.pageNo = 1
    getList()
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
  }

  /**打开表格表头设置**/
  const tableTitleSet = ref()
  const openTableTitleSet = () => {
    let code = 'salaryCostProject'
    tableTitleSet.value.open(tableTitleList.value, code)
  }

  /** 导出按钮操作 */
  const exportRef = ref()
  const handleExport = () => {
    exportRef.value.open()
  }
  // 导出
  const downloadFun = async () => {
    const val = exportRef.value.params
    let params = {
      fileName: val.name,
      ids: ''
    }
    if (val.range === 'all') {
      params.ids = ''
    } else {
      params.ids = selectList.value.map((item) => item.id).join(',')
    }
    salaryCostProjectApi.exportSalaryCostProjectExcel(params).then((res) => {
      download.excel(res, val.name)
      clearSelectData()
    })
  }

  //清空多选
  const clearSelectData = () => {
    selectList.value = []
    multipleTableRef.value.clearSelection()
  }

  /** 初始化 **/
  const tableHeight = ref(0)
  onMounted(async () => {
    const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
    tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 70
    getList()
  })
</script>
